package com.zhida.smartcontrol.mvp;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.dyhdyh.widget.loadingbar2.LoadingBar;
import com.jay.tools.base.BaseDialogFragment;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.utils.ClickUtil;
import com.zhida.smartcontrol.utils.CustomDialogFactory;

import java.lang.reflect.ParameterizedType;
import java.util.Timer;
import java.util.TimerTask;

/**
 * author: tanjianpei
 * date: 2019/8/19 019 15:10
 * description:
 */
public abstract class MVPBaseDialogFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends BaseDialogFragment implements BaseView {
    protected T mPresenter;

    @Override
    protected void initPresenter() {
        mPresenter = getInstance(this, 1);
        mPresenter.attachView((V) this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LoadingBar.release();
        if (mPresenter != null)
            mPresenter.detachView();
    }

//    private Handler timeHandler = new Handler() {
//
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what == 1) {
//               hideLoading();
//            }
//        }
//    };
//
//    public void setTimer() {
//        Timer timer=new Timer();
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//                timer.cancel();
//                Message message = Message.obtain();
//                message.what = 1;
//                timeHandler.sendMessage(message);
//            }
//        };
//        timer.schedule(task, 5000, 5000);
//    }


    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Override
    public void showLoading(String msg) {
        LoadingBar.dialog(mActivity)
                //通过工厂设置样式
                .setFactory(new CustomDialogFactory(msg))
                //通过View设置样式
//                .setFactoryFromView(view)
                //通过布局ID设置样式
//                .setFactoryFromResource(R.layout.layout_loading)
                //携带参数
                .extras(new Object[]{})
                .show();
    }

    @Override
    public void hideLoading() {
        LoadingBar.dialog(mActivity).cancel();
    }

    @Override
    public void showMsg(String msg) {
        toast(msg);
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
